package com.itheima.app.manager;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.itheima.autoconfig.face.AipFaceTemplate;
import com.itheima.autoconfig.huanxin.HuanXinTemplate;
import com.itheima.autoconfig.oss.OssTemplate;
import com.itheima.autoconfig.sms.SmsTemplate;
import com.itheima.domain.db.Log;
import com.itheima.domain.db.User;
import com.itheima.domain.db.UserInfo;
import com.itheima.service.db.UserInfoService;
import com.itheima.service.db.UserService;
import com.itheima.util.ConstantUtil;
import com.itheima.util.JwtUtil;
import com.itheima.vo.ErrorResult;
import com.itheima.vo.UserInfoVo;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.time.Duration;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Component
public class UserManager {

    @DubboReference
    private UserService userService;

    // 保存用户
    public ResponseEntity save(User user) {
        return ResponseEntity.ok(userService.save(user));
    }

    // 查询用户
    public ResponseEntity findByPhone(String phone) {
        int i = 1 / 0;
        User user = userService.findByPhone(phone);
        return ResponseEntity.ok(user);
    }

    @Autowired
    private SmsTemplate smsTemplate;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    // 发送短信验证码
    public void sendSms(String phone) {
        // 1.生成6位随机数
        String smsCode = RandomUtil.randomNumbers(6);
        smsCode = "123456";

        // 2.调用阿里云发送
        // smsTemplate.sendSms(phone, smsCode);

        // 3.将验证码存储到redis中   ofMinutes分钟  ofMillis毫秒
        stringRedisTemplate.opsForValue().set(ConstantUtil.SMS_CODE + phone, smsCode, Duration.ofMinutes(5));
    }

    @Autowired
    private HuanXinTemplate huanXinTemplate;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    // 注册、登录功能
    public ResponseEntity loginAndRegister(String phone, String verificationCode) {
        // 声明一个返回将结果
        Map<String, Object> resultMap = new HashMap<>();

        // 1.获取redis中验证码
        String codeFromRedis = stringRedisTemplate.opsForValue().get(ConstantUtil.SMS_CODE + phone);
        // 2.对比验证码是否一致
        if (!StrUtil.equals(verificationCode, codeFromRedis)) {
            return ResponseEntity.status(500).body(ErrorResult.loginError());
        }
        // 3.根据手机号查询用户
        User user = userService.findByPhone(phone);

        String type;

        if (user != null) { // 老用户
            resultMap.put("isNew", false);
            type = "0101";
        } else {// 新用户
            resultMap.put("isNew", true);
            // 帮新用户注册
            user = new User();
            user.setPhone(phone);
            user.setPassword(ConstantUtil.INIT_PASSWORD);
            Long newUserId = userService.save(user);
            user.setId(newUserId);
            // 注册到环信
            huanXinTemplate.register("HX" + newUserId);

            type = "0102";
        }
        // 4.使用jwt制作令牌
        user.setPassword(null);
        Map<String, Object> claims = BeanUtil.beanToMap(user);
        String token = JwtUtil.createToken(claims);
        // 5.redis存储用户信息
        String json = JSON.toJSONString(user);
        stringRedisTemplate.opsForValue().set(ConstantUtil.USER_TOKEN + token, json, Duration.ofDays(7));

        // 清除短信验证码
        stringRedisTemplate.delete(ConstantUtil.SMS_CODE + phone);

        // 6.返回结果
        resultMap.put("token", token);

        // 7.发送mq的日志消息
        Log log = new Log();
        log.setUserId(user.getId());
        log.setLogTime(DateUtil.formatDate(new Date()));
        log.setPlace("北京顺义");
        log.setEquipment("国产小辣椒");
        log.setType(type);
        rabbitTemplate.convertAndSend("tanhua.log", log);

        return ResponseEntity.ok(resultMap);
    }

    @DubboReference
    private UserInfoService userInfoService;

    // 完善用户基础信息
    public void saveUserInfoBase(UserInfo userInfo, String token) {
        // 1.解析token获取user对象
        User user = findUserByToken(token);
        // 2.给userInfo设置userId
        userInfo.setId(user.getId());
        // 3.调用rpc保存
        userInfoService.save(userInfo);

    }

    // 解析token获取user对象
    public User findUserByToken(String token) {
        // 1.对token进行非空判断
        if (StrUtil.isEmpty(token)) {
            return null;
        }
        // 2.获取redis中user对象
        String json = stringRedisTemplate.opsForValue().get(ConstantUtil.USER_TOKEN + token);

        // 3.对json进行非空判断
        if (StrUtil.isEmpty(json)) {
            return null;
        }

        // 4.转换为user对象
        User user = JSON.parseObject(json, User.class);

        // 5.对redis的user进行续期
        stringRedisTemplate.opsForValue().set(ConstantUtil.USER_TOKEN + token, json, Duration.ofDays(7));

        return user;
    }

    @Autowired
    private AipFaceTemplate aipFaceTemplate;

    @Autowired
    private OssTemplate ossTemplate;

    // 完善用户头像信息
    public ResponseEntity saveUserInfoHead(MultipartFile headPhoto, String token) throws Exception {
        // 1.解析token获取user对象
        User user = findUserByToken(token);
        // 2.人脸检测
        boolean detect = aipFaceTemplate.detect(headPhoto.getBytes());
        if (detect == false) { // 非人脸
            return ResponseEntity.status(500).body(ErrorResult.faceError());
        }
        // 3.上传图片到oss
        String picUrl = ossTemplate.upload(headPhoto.getOriginalFilename(), headPhoto.getInputStream());
        // 4.组装userInfo
        UserInfo userInfo = new UserInfo();
        userInfo.setId(user.getId()); // 用户id
        userInfo.setAvatar(picUrl); // 头像
        userInfo.setCoverPic(picUrl); // 背景
        // 5.调用rpc更新
        userInfoService.update(userInfo);

        return ResponseEntity.ok(null);
    }

    // 查询用户信息
    public ResponseEntity findUserInfoVo(Long id) {
        // 1.调用rpc查询userInfo
        UserInfo userInfo = userInfoService.findUserInfoById(id);
        // 2.封装userInfoVo
        UserInfoVo userInfoVo = new UserInfoVo();
        BeanUtil.copyProperties(userInfo, userInfoVo);
        // 3.返回
        return ResponseEntity.ok(userInfoVo);
    }

    // 修改用户基础信息
    public void updateUserInfoBase(UserInfo userInfo, String token) {
        // 1.解析token获取user对象
        User user = findUserByToken(token);
        // 2.设置userId到userInfo中
        userInfo.setId(user.getId());
        // 3.调用rpc完成更新
        userInfoService.update(userInfo);
    }
}
